package com.banciyuan.bcywebview.biz.post.succ;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.share.JumpDialog;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sns.SnsUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PostCore;
import de.greenrobot.daoexample.model.PostSucc;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.User;

/**
 * Created by squall on 2016/6/20.
 */
public class PostSuccActivity extends BaseActivity implements View.OnClickListener, WbShareCallback {

    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private DetailType detailType;
    private ImageView iv_qq;
    private ImageView iv_qqzone;
    private ImageView iv_weibo;
    private ImageView iv_friend;
    private ImageView iv_wechat;
    private TextView count_tv;
    private TextView tag_tg;
    private TextView share_tv;
    private TextView post_text;
    private LinearLayout data_ll;
    private CheckBox sendInvited_radio;

    private LinearLayout count_container;
    private LinearLayout invited_container;
    private List<String> uids = new ArrayList<>();
    private List<User> users = new ArrayList<>();

    private WbShareHandler shareHandler;
    private IWXAPI mWxApi;
    private Tencent mTencent;
    private Map<String, String> map;

    private boolean is_invited;

    private JumpDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initArgs();
        setRootView();
        initUi();
        initActionbar();
        initData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        shareHandler.doResultIntent(intent, this);
    }

    private void setRootView() {
        if (detailType != null && (detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP)) {
            setContentView(R.layout.activity_grouppost_share);
        } else {
            setContentView(R.layout.activity_post_share);
        }
    }

    @Override
    protected void initUi() {
        iv_qq = (ImageView) findViewById(R.id.iv_qq);
        iv_qqzone = (ImageView) findViewById(R.id.iv_qqzone);
        iv_weibo = (ImageView) findViewById(R.id.iv_weibo);
        iv_friend = (ImageView) findViewById(R.id.iv_friend);
        iv_wechat = (ImageView) findViewById(R.id.iv_wechat);
        count_tv = (TextView) findViewById(R.id.count_tv);
        tag_tg = (TextView) findViewById(R.id.tag_container);
        share_tv = (TextView) findViewById(R.id.share_tv);
        post_text = (TextView) findViewById(R.id.post_succ);
        data_ll = (LinearLayout) findViewById(R.id.data_container);
        count_container = (LinearLayout) findViewById(R.id.count_container);
        invited_container = (LinearLayout) findViewById(R.id.invited_container);
        sendInvited_radio = (CheckBox) findViewById(R.id.send_invited_radio);

        count_container.setVisibility(View.VISIBLE);
        if (detailType != null && detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_DAILY) {
            share_tv.setText(String.format(getString(R.string.share_to_friend_post), getString(R.string.daily)));
            invited_container.setVisibility(View.GONE);
        } else if (detailType != null && (detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP || detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP_TEAM)) {
            share_tv.setText(getString(R.string.share_to_friend_post_group));
            count_container.setVisibility(View.GONE);
            invited_container.setVisibility(View.VISIBLE);
        } else {
            share_tv.setText(String.format(getString(R.string.share_to_friend_post), getString(R.string.create_unit)));
            invited_container.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initAction() {
        iv_qq.setOnClickListener(this);
        iv_qqzone.setOnClickListener(this);
        iv_weibo.setOnClickListener(this);
        iv_friend.setOnClickListener(this);
        iv_wechat.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL;
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        switch (detailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url += CoserApi.getSharePost();
                pairs.add(new BcyPair(HttpUtils.RPID, detailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url += IllustApi.getSharePost();
                pairs.add(new BcyPair(HttpUtils.RPID, detailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url += NovelApi.getSharePost();
                pairs.add(new BcyPair(HttpUtils.RPID, detailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url += DailyApi.getSharePost();
                pairs.add(new BcyPair(HttpUtils.UDID, detailType.getUd_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP_TEAM:
                url += GroupApi.getShareGroup();
                pairs.add(new BcyPair(HttpUtils.GID, detailType.getGid()));
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                url += GroupApi.getSharePost();
                pairs.add(new BcyPair(HttpUtils.GID, detailType.getGid()));
                pairs.add(new BcyPair(HttpUtils.POSTID, detailType.getPost_id()));
                break;
        }
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getContext())) {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        PostSucc postSucc = gson.fromJson(result, PostSucc.class);
                        renderData(postSucc);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };

        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        VolleyQueue.getRquest(this).add(stringRequestParam);
    }

    private void renderData(PostSucc postSucc) {
        if (postSucc != null) {
            map = new HashMap<>();
            map.put("title", postSucc.getShare_title());
            map.put("url", postSucc.getShare_url());
            map.put("content", postSucc.getShare_plain());
            map.put("imagePath", postSucc.getShare_cover());
            if (!TextUtils.isEmpty(postSucc.getAll_follow_count())) {
                count_tv.setText(postSucc.getAll_follow_count());
            }
            List<TagDetail> templist = new ArrayList<>();
            if (postSucc.getPost_core() != null) {
                PostCore p = postSucc.getPost_core();
                if (!TextUtils.isEmpty(p.getName())) {
                    TagDetail tagDetail = new TagDetail();
                    tagDetail.setTag_name(p.getName());
                    templist.add(tagDetail);
                }
            }
            if (postSucc.getPost_tags() != null && !postSucc.getPost_tags().isEmpty()) {
                templist.addAll(postSucc.getPost_tags());
            }
            if (!StringUtil.notNullEqual(postSucc.getAll_follow_count(), "0")) {
                post_text.setVisibility(View.GONE);
                data_ll.setVisibility(View.VISIBLE);
                ((View) (count_tv.getParent())).setVisibility(View.VISIBLE);
                StringBuilder sb = new StringBuilder();
                for (TagDetail t : templist) {
                    sb.append(t.getTag_name() + "\t\t");
                }
                tag_tg.setText(sb.toString().trim());
            } else {
                post_text.setVisibility(View.VISIBLE);
                data_ll.setVisibility(View.GONE);
                ((View) (count_tv.getParent())).setVisibility(View.GONE);
            }
            if (detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP || detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP_TEAM) {
                this.users = postSucc.getInvited_users();
                renderUser();
            }
        }
        initAction();
    }

    private void renderUser() {
        if (users != null && !users.isEmpty()) {
            invited_container.setVisibility(View.VISIBLE);
            LinearLayout img_container = (LinearLayout) invited_container.getChildAt(0);
            for (int i = 0; i < img_container.getChildCount(); i++) {
                ImageView iv = (ImageView) img_container.getChildAt(i);
                if (i < users.size()) {
                    ImageLoader.getInstance().displayImage(users.get(i).getAvatar(), iv, ImageOptions.optionHead);
                }
            }
        } else {
            invited_container.setVisibility(View.GONE);
        }

    }

    @Override
    protected void initArgs() {
        detailType = (DetailType) getIntent().getSerializableExtra("detailtype");
        mTencent = Tencent.createInstance(MyConstants.QQ_LOGIN_APP_ID, getContext());
        //初始化微博分享

        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();
        //初始化微信分享
        mWxApi = WXAPIFactory.createWXAPI(this, MyConstants.WEIXIN_APP_ID, true);
        mWxApi.registerApp(MyConstants.WEIXIN_APP_ID);
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.post_succ));
        TextView finish = (TextView) mActionBarView.findViewById(R.id.base_action_bar_home_text_item);
        finish.setTextColor(getResources().getColor(R.color.pink));
        if (detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP || detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GROUP_TEAM) {
            mActionbarHelper.addItemOneText(getString(R.string.finish));
            finish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    invitedPeople();
                }
            });
        }
    }

    private void invitedPeople() {
        if (sendInvited_radio.isChecked()) {
            if (!is_invited) {
                is_invited = true;
                for (User u : users) {
                    uids.add(u.getUid());
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < uids.size(); i++) {
                    if (i == uids.size() - 1) {
                        sb.append(uids.get(i));
                    } else {
                        sb.append(uids.get(i) + ",");
                    }
                }
                String url = HttpUtils.BASE_URL + GroupApi.getInvitedUser();
                List<BcyPair> pairs = new ArrayList<>();
                pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
                pairs.add(new BcyPair(HttpUtils.GID, detailType.getGid()));
                pairs.add(new BcyPair("uids", sb.toString()));

                Response.Listener<String> onSucc = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        finish();
                    }
                };

                Response.ErrorListener onError = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        finish();
                    }
                };
                HashMap<String, String> map = HttpUtils.getData(pairs);
                StringRequestParam request = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
                VolleyQueue.getRquest(getContext()).add(request);
            }
        } else {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        if (map == null) return;
        switch (v.getId()) {
            case R.id.iv_qq:
                SnsUtil.share2QQ(this, map, mTencent);
                break;
            case R.id.iv_qqzone:
                SnsUtil.shareToQQZone(this, map, mTencent);
                break;
            case R.id.iv_weibo:
                showWeiboJumpDialog();
                SnsUtil.share2Weibo(shareHandler, map);
                break;
            case R.id.iv_friend:
                if (mWxApi.isWXAppInstalled()) {
                    SnsUtil.share2Circle(this, map, mWxApi);
                } else {
                    MyToast.show(this, getString(R.string.weixin_notinstalled));
                }
                break;
            case R.id.iv_wechat:
                if (mWxApi.isWXAppInstalled()) {
                    SnsUtil.share2Weixin(this, map, mWxApi);
                } else {
                    MyToast.show(this, getString(R.string.weixin_notinstalled));
                }
                break;
        }
    }

    private void showWeiboJumpDialog() {
        JumpDialog.Builder builder = new JumpDialog.Builder(this);
        dialog = builder.create();
        dialog.show();
    }

    private void dismissDialog() {
        if (dialog != null && !isFinishing() && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onWbShareSuccess() {
        dismissDialog();
        MyToast.show(this, getString(R.string.weibosdk_demo_toast_share_success));
    }

    @Override
    public void onWbShareCancel() {
        dismissDialog();
        MyToast.show(this, getString(R.string.weibosdk_demo_toast_share_cancel));

    }

    @Override
    public void onWbShareFail() {
        dismissDialog();
        MyToast.show(this, getString(R.string.weibosdk_demo_toast_share_success));
    }
}
